package com.gome.extract;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.gome.extract.common.AppConfiguer;
import com.gome.extract.common.GlobalUtils;

public class HashDict<Kty> extends GlobalUtils
{
//	private static final String ENCODE = "UTF8";
//    private static final String SEP = "|||";
	private static Logger logger = Logger.getLogger(FileReader.class);
	private HashMap<Kty, Integer> mHashDict = new HashMap<Kty, Integer>();
	private StaticHash<Kty> mStaticDict = new StaticHash<Kty>();
	private String mDictName = "";
	
	public HashDict()
	{	
	}
	
	public HashDict(String dictName)
	{
		mDictName = dictName;
	}
	
	public boolean hasKey(Kty k)
	{
		return mHashDict.containsKey(k);
	}
	
	
	public int add(Kty k)
	{
		if(mHashDict.containsKey(k))
			return mHashDict.get(k);
		
		int id = mHashDict.size();
		mHashDict.put(k, id);
		return id;
	}
	
	public int get(Kty k)
	{
		if(mHashDict.containsKey(k))
			return mHashDict.get(k);
		
		return -1;
	}
	
	public int size()
	{
		return mHashDict.size();
	}
	
	public void print()
	{
		for(Entry<Kty, Integer > entry : mHashDict.entrySet())
		{
			Kty k = entry.getKey();
			Integer v = entry.getValue();
			String val = k  + TAB + v;
			logger.debug(val);
		}
	}
	
	public boolean write()
	{
//		int bucketNum = mStaticDict.getBucketNum(mHashDict.size());
//		return mStaticDict.writeToHashFile(mHashDict, bucketNum, mDictName);
		
		try 
		{
			FileOutputStream out = new FileOutputStream(mDictName);
			for(Entry< Kty, Integer > entry : mHashDict.entrySet())
			{
				String k = String.valueOf(entry.getKey());
				Integer v = entry.getValue();
				String val = k  + "\t" + v + "\n";
				out.write(val.getBytes("utf-8"));
			}
	    	out.close();
	    	
	    	return true;
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			logger.error(AppConfiguer.getTrace(e));
			return false;
		}
		
		
	}
	
	public boolean load()
	{
//		return mStaticDict.loadHashFileToMemory(mDictName);
		
		if(mHashDict.size()!=0)
    		return false;
    	try
    	{
    		 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream( new File(mDictName)), ENCODE) );
             String strContent="";
             String line;
             
             while ( (line = reader.readLine()) != null)
             {
            	 String[] sa = line.split(TAB);
            	 mHashDict.put((Kty)sa[0], Integer.parseInt(sa[1]));
             }
             reader.close();
             return true;
             
    	}
    	catch(Exception e)
    	{
    		logger.error(AppConfiguer.getTrace(e));
    		return false;
    	}
    	
	}
}

